package admin

import (
	"MembershipRegist/db"
	"MembershipRegist/models"
)

func (c *Controller) OrganizationInsert() {
	name := c.GetString("name")
	introduction := c.GetString("introduction")

	if name == "" || introduction == "" {
		c.ResponseFailed(201, "请输入社团名称和简介")
		return
	}

	organization := models.Organization{
		Name:         name,
		Introduction: introduction,
	}

	if value := db.DB.Create(&organization); value.Error != nil {
		c.ResponseFailed(202, "录入社团信息失败")
		return
	}

	c.ResponseSuccess()
}

func (c *Controller) OrganizationDelete() {
	organizationID, err := c.GetInt("organization_id")
	if err != nil {
		c.ResponseFailed(201, "organization_id 不合法")
		return
	}

	var adminCount int
	db.DB.Model(&models.OrganizationAdmin{}).
		Where("organization_id = ?", organizationID).Count(&adminCount)

	if adminCount != 0 {
		c.ResponseFailed(202, "社团存在管理员,无法删除(请先删除所有管理员)")
		return
	}

	if value := db.DB.Unscoped().Delete(&models.Organization{}, "id = ?", organizationID); value.Error != nil {
		c.ResponseFailed(203, "删除社团失败")
		return
	}

	c.ResponseSuccess()
}

func (c *Controller) OrganizationUpdate() {
	organizationID, err := c.GetInt("organization_id")
	if err != nil {
		c.ResponseFailed(201, "organization_id 不合法")
		return
	}

	name := c.GetString("name")
	introduction := c.GetString("introduction")
	updateValue := make(map[string]interface{})
	if name != "" {
		updateValue["name"] = name
	}
	if introduction != "" {
		updateValue["introduction"] = introduction
	}

	db.DB.Model(&models.Organization{}).Where("id = ?", organizationID).
		Updates(updateValue)

	c.ResponseSuccess()
}
